package org.jeecg.modules.htxincailiao.industry.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RequestUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.account.entity.HTMember;
import org.jeecg.modules.htxincailiao.account.entity.HTMerchant;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.account.service.IHTMemberService;
import org.jeecg.modules.htxincailiao.account.service.IHTMerchantService;
import org.jeecg.modules.htxincailiao.industry.domain.dto.HTIndustryCheckDTO;
import org.jeecg.modules.htxincailiao.industry.entity.HTIndustryExhibition;
import org.jeecg.modules.htxincailiao.industry.entity.HTIndustryExhibitionCheck;
import org.jeecg.modules.htxincailiao.industry.service.IHTIndustryExhibitionCheckService;
import org.jeecg.modules.htxincailiao.industry.service.IHTIndustryExhibitionService;
import org.jeecg.modules.htxincailiao.order.domain.vo.HTOrderVO;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: ht_industry_exhibition_check
 * @Author: jeecg-boot
 * @Date: 2021-12-21 17:55:12
 * @Version: V1.0
 */
@Api(tags = "ht_industry_exhibition_check")
@RestController
@RequestMapping("/industry/hTIndustryExhibitionCheck")
@Slf4j
public class HTIndustryExhibitionCheckController extends JeecgController<HTIndustryExhibitionCheck, IHTIndustryExhibitionCheckService> {
	@Resource
	private IHTIndustryExhibitionCheckService hTIndustryExhibitionCheckService;

	@Resource
	private IHTIndustryExhibitionService industryExhibitionService;

	@Resource
	private IHTAccountService accountService;

	@Resource
	private IHTMemberService memberService;


	@Resource
	private IHTMerchantService merchantService;


	/**
	 * 分页列表查询
	 *
	 * @param hTIndustryExhibitionCheck
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ht_industry_exhibition_check-分页列表查询")
	@ApiOperation(value = "ht_industry_exhibition_check-分页列表查询", notes = "ht_industry_exhibition_check-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HTIndustryExhibitionCheck hTIndustryExhibitionCheck,
								   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
								   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HTIndustryExhibitionCheck> queryWrapper = QueryGenerator.initQueryWrapper(hTIndustryExhibitionCheck, req.getParameterMap());
		Page<HTIndustryExhibitionCheck> page = new Page<HTIndustryExhibitionCheck>(pageNo, pageSize);
		IPage<HTIndustryExhibitionCheck> pageList = hTIndustryExhibitionCheckService.page(page, queryWrapper);

		List<HTIndustryExhibitionCheck> list = pageList.getRecords();
		for (HTIndustryExhibitionCheck check : list) {
			HTMember user = memberService.getById(check.getUserId());
			if (oConvertUtils.isNotEmpty(user)) {
				check.setPhoneNumber(user.getPhoneNumber());
			} else {
				HTMerchant merchant = merchantService.getById(check.getUserId());
				if (oConvertUtils.isNotEmpty(merchant)) {
					check.setPhoneNumber(merchant.getPhoneNumber());
					check.setEnterpriseName(merchant.getEnterpriseName());
				}
			}
		}
		return Result.OK(pageList);
	}

	/**
	 * 分页列表查询
	 *
	 * @param dto
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ht_industry_exhibition_check-分页列表查询")
	@ApiOperation(value = "ht_industry_exhibition_check-分页列表查询", notes = "ht_industry_exhibition_check-分页列表查询")
	@PostMapping(value = "/orderedList")
	public Result<?> queryOrderedList(HttpServletRequest req, @RequestBody HTIndustryCheckDTO dto) {

		Result<List<HTIndustryExhibitionCheck>> result = new Result<>();
		String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
		String username = JwtUtil.getUsername(token);
		HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
		if (oConvertUtils.isNotEmpty(user)) {
			List<HTIndustryExhibitionCheck> list = hTIndustryExhibitionCheckService.findAll(dto.getExhibitionId(), user.getId());
			result.setResult(list);
		} else {
			result.error500("请选登录");
		}

		return result;
	}

	/**
	 * 分页列表查询
	 *
	 * @param hTIndustryExhibitionCheck
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ht_industry_exhibition_check-分页列表查询")
	@ApiOperation(value = "ht_industry_exhibition_check-分页列表查询", notes = "ht_industry_exhibition_check-分页列表查询")
	@RequestMapping(value = "/userAppliedList", method = {RequestMethod.GET, RequestMethod.POST})
	public Result<?> queryPageUserAppliedList(HTIndustryExhibitionCheck hTIndustryExhibitionCheck,
											  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
											  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
											  HttpServletRequest req) {
		if (req.getMethod().equals("POST")) {
			String line = RequestUtil.getPostParam(req);
			if (oConvertUtils.isNotEmpty(line)) {
				hTIndustryExhibitionCheck = JSONObject.parseObject(line, HTIndustryExhibitionCheck.class);
				pageNo = oConvertUtils.isNotEmpty(hTIndustryExhibitionCheck.getPageNo()) ? hTIndustryExhibitionCheck.getPageNo() : pageNo;
				pageSize = oConvertUtils.isNotEmpty(hTIndustryExhibitionCheck.getPageSize()) ? hTIndustryExhibitionCheck.getPageSize() : pageSize;
			}
		}

		Result<IPage<HTOrderVO>> result = new Result<>();
		String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
		String username = JwtUtil.getUsername(token);
		HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
		if (oConvertUtils.isNotEmpty(user)) {
			hTIndustryExhibitionCheck.setUserId(user.getId());
		}

		QueryWrapper<HTIndustryExhibitionCheck> queryWrapper = QueryGenerator.initQueryWrapper(hTIndustryExhibitionCheck, req.getParameterMap());
		Page<HTIndustryExhibitionCheck> page = new Page<HTIndustryExhibitionCheck>(pageNo, pageSize);
		IPage<HTIndustryExhibitionCheck> pageList = hTIndustryExhibitionCheckService.page(page, queryWrapper);

		return Result.OK(pageList);
	}


	/**
	 * 编辑
	 *
	 * @param dto
	 * @return
	 */
	@AutoLog(value = "ht_industry_exhibition_check-编辑")
	@ApiOperation(value = "ht_industry_exhibition_check-编辑", notes = "ht_industry_exhibition_check-编辑")
	@PostMapping(value = "/getUserCheck")
	public Result<?> getUserCheck(HttpServletRequest req, @Valid @RequestBody HTIndustryCheckDTO dto) {
		Result<HTIndustryExhibitionCheck> result = new Result<>();
		String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
		String username = JwtUtil.getUsername(token);
		HTPlatformUser user = accountService.queryFrontendUserByUsername(username);

		if (oConvertUtils.isNotEmpty(user)) {
			HTIndustryExhibitionCheck check = hTIndustryExhibitionCheckService.queryByUser(dto.getExhibitionId(), user.getId());
			result.setResult(check);
		} else {
			result.error500("请先登录");
		}
		return result;
	}


	/**
	 * 编辑
	 *
	 * @param dto
	 * @return
	 */
	@AutoLog(value = "ht_industry_exhibition_check-编辑")
	@ApiOperation(value = "ht_industry_exhibition_check-编辑", notes = "ht_industry_exhibition_check-编辑")
	@PostMapping(value = "/userCheckIn")
	public Result<?> userCheckIn(HttpServletRequest req, @Valid @RequestBody HTIndustryCheckDTO dto) {
		Result<HTIndustryExhibitionCheck> result = new Result<>();
		String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
		String username = JwtUtil.getUsername(token);
		HTPlatformUser user = accountService.queryFrontendUserByUsername(username);

		if (oConvertUtils.isNotEmpty(user)) {
			HTIndustryExhibition exhibition = industryExhibitionService.getById(dto.getExhibitionId());
			HTIndustryExhibitionCheck check = hTIndustryExhibitionCheckService.queryByUser(dto.getExhibitionId(), user.getId());
			if (isPaymentExhibition(exhibition)) {
				check = handlePaymentExhibitionCheck(dto, user, check);
				result.setResult(check);
			} else {

				HTIndustryExhibitionCheck checkedInCheck = handleFreeExhibitionCheck(dto, user, check);
				if (oConvertUtils.isNotEmpty(checkedInCheck)) {
					result.setResult(checkedInCheck);
				}
			}
		} else {
			result.error500("请先登录");
		}
		return result;
	}

	private HTIndustryExhibitionCheck handleFreeExhibitionCheck(HTIndustryCheckDTO dto,
														  HTPlatformUser user,
														  HTIndustryExhibitionCheck check) {
		if (oConvertUtils.isEmpty(check)) {
			check = hTIndustryExhibitionCheckService.queryByBuyerId(dto.getExhibitionId(), user.getId());
			//免费会议 check为空时自动创建check 自动签到
			if (oConvertUtils.isEmpty(check)) {
				check = new HTIndustryExhibitionCheck();
				check.setBuyerId(user.getId());
				check.setExhibitionId(dto.getExhibitionId());

				try {
					hTIndustryExhibitionCheckService.save(check);
				} catch (Exception e) {
					throw new JeecgBootException("签到失败请稍后尝试");
				}
			}
		}
		updateCheck(dto, user, check);
		return check;
	}

	private HTIndustryExhibitionCheck handlePaymentExhibitionCheck(HTIndustryCheckDTO dto,
															 HTPlatformUser user,
															 HTIndustryExhibitionCheck check) {
//        System.out.printf("\n\n\n handlePaymentExhibitionCheck %s \n\n\n", JSONObject.toJSONString(check));
		boolean success = false;
//        验证码未签到
		if (oConvertUtils.isEmpty(check)) {
			if (oConvertUtils.isNotEmpty(dto.getCode())) {
				check = hTIndustryExhibitionCheckService.queryByCode(dto.getExhibitionId(), dto.getCode());
			} else {
				throw new JeecgBootException("入场码不能为空");
			}
		}

		if (oConvertUtils.isNotEmpty(check)) {
			success = updateCheck(dto, user, check);
		} else {
			throw new JeecgBootException("未报名或入场码有误");
		}

		return check;
	}

	private boolean updateCheck(HTIndustryCheckDTO dto,
								HTPlatformUser user,
								HTIndustryExhibitionCheck check) {
		boolean success = false;
		Integer checkSerialNumber = hTIndustryExhibitionCheckService.getCheckSerialNumber(dto.getExhibitionId());

		check.setExhibitionId(dto.getExhibitionId());
		check.setUserId(user.getId());
		check.setCode(check.getCode());
		check.setIsCheckedIn(1);

		if (check.getCheckSerialNumber() == 0) {
			check.setCheckSerialNumber(checkSerialNumber);
		}

		if (oConvertUtils.isNotEmpty(dto.getEnterpriseName())) {
			check.setEnterpriseName(dto.getEnterpriseName());
		}

		if (oConvertUtils.isNotEmpty(dto.getParticipant())) {
			check.setParticipant(dto.getParticipant());
		} else {
			String participant = user.getRealName();
			if (oConvertUtils.isEmpty(participant)) participant = user.getPhoneNumber();
			if (oConvertUtils.isEmpty(participant)) participant = user.getUsername();
			check.setParticipant(participant);
		}
		try {
			success = hTIndustryExhibitionCheckService.updateById(check);
		} catch (Exception e) {
			throw new JeecgBootException("签到失败请稍后尝试");
		}

		return success;
	}

	private boolean isPaymentExhibition(HTIndustryExhibition exhibition) {
		return oConvertUtils.isNotEmpty(exhibition) &&
				oConvertUtils.isNotEmpty(exhibition.getAudienceCost()) &&
				exhibition.getAudienceCost().floatValue() > 0;
	}

	/**
	 * 添加
	 *
	 * @param hTIndustryExhibitionCheck
	 * @return
	 */
	@AutoLog(value = "ht_industry_exhibition_check-添加")
	@ApiOperation(value = "ht_industry_exhibition_check-添加", notes = "ht_industry_exhibition_check-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody HTIndustryExhibitionCheck hTIndustryExhibitionCheck) {
		hTIndustryExhibitionCheckService.save(hTIndustryExhibitionCheck);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 *
	 * @param hTIndustryExhibitionCheck
	 * @return
	 */
	@AutoLog(value = "ht_industry_exhibition_check-编辑")
	@ApiOperation(value = "ht_industry_exhibition_check-编辑", notes = "ht_industry_exhibition_check-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody HTIndustryExhibitionCheck hTIndustryExhibitionCheck) {
		hTIndustryExhibitionCheckService.updateById(hTIndustryExhibitionCheck);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_industry_exhibition_check-通过id删除")
	@ApiOperation(value = "ht_industry_exhibition_check-通过id删除", notes = "ht_industry_exhibition_check-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
		hTIndustryExhibitionCheckService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "ht_industry_exhibition_check-批量删除")
	@ApiOperation(value = "ht_industry_exhibition_check-批量删除", notes = "ht_industry_exhibition_check-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		this.hTIndustryExhibitionCheckService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_industry_exhibition_check-通过id查询")
	@ApiOperation(value = "ht_industry_exhibition_check-通过id查询", notes = "ht_industry_exhibition_check-通过id查询")
	@RequestMapping(value = "/queryById", method = {RequestMethod.GET, RequestMethod.POST})
	public Result<?> queryById(HttpServletRequest req, @RequestParam(name = "id", required = false) String id) {
		if (req.getMethod().equals("POST")) {
			String line = RequestUtil.getPostParam(req);
			if (oConvertUtils.isNotEmpty(line)) {
				HTIndustryExhibitionCheck hTIndustryExhibitionCheck = JSONObject.parseObject(line, HTIndustryExhibitionCheck.class);
				id = hTIndustryExhibitionCheck.getId();
			}
		}

		HTIndustryExhibitionCheck hTIndustryExhibitionCheck = hTIndustryExhibitionCheckService.getById(id);
		if (hTIndustryExhibitionCheck == null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hTIndustryExhibitionCheck);
	}

	/**
	 * 导出excel
	 *
	 * @param req
	 * @param hTIndustryExhibitionCheck
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest req, HTIndustryExhibitionCheck hTIndustryExhibitionCheck) {
		QueryWrapper<HTIndustryExhibitionCheck> queryWrapper = QueryGenerator.initQueryWrapper(hTIndustryExhibitionCheck, req.getParameterMap());
		Page<HTIndustryExhibitionCheck> page = new Page<HTIndustryExhibitionCheck>(1, 99999999);
		IPage<HTIndustryExhibitionCheck> pageList = hTIndustryExhibitionCheckService.page(page, queryWrapper);

		List<HTIndustryExhibitionCheck> list = pageList.getRecords();
		for (HTIndustryExhibitionCheck check : list) {
			HTPlatformUser user = accountService.queryUserById(check.getUserId());
			if (oConvertUtils.isNotEmpty(user)) {
				check.setPhoneNumber(user.getPhoneNumber());
			}

		}

		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "ht_industry_exhibition_check");
		mv.addObject(NormalExcelConstants.CLASS, HTIndustryExhibitionCheck.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("ht_industry_exhibition_check", "导出人：admin", "ht_industry_exhibition_check"));
		mv.addObject(NormalExcelConstants.DATA_LIST, list);

		return mv;


//        return super.exportXls(req, hTIndustryExhibitionCheck, HTIndustryExhibitionCheck.class, "ht_industry_exhibition_check");
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, HTIndustryExhibitionCheck.class);
	}

}
